import os
import random
import sys
import uuid

import django
import faker

back = os.path.dirname
BASE_DIR = back(back(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

def init_good_category():
    """初始化商品分类"""
    print('清空 Categories ')
    Categories.objects.all().delete()
    print('往 Categories 添加 数据')
    for i in range(10):
        instance = Categories.objects.create(
            name=fake.word()+str(i),
            is_show=random.choice([True, False])
        )
        instance.save()
    queryset = Categories.objects.all()
    for i in range(100):
        instance = Categories.objects.create(
            name = fake.word()+str(i),
            is_show=random.choice([True, False]),
            pid=random.choice(queryset)
        )
        instance.save()

def init_good_info():
    """初始化商品分类"""
    print('清空 Goods ')
    Goods.objects.all().delete()
    print('往 Goods 添加 数据')
    for i in range(40):
        instance = Goods.objects.create(
            name=fake.word()+str(i),
            price=round(random.random() * 100, 2),
            number=random.randint(0, 10),
            weight=round(random.random() * 100, 2),
            introduction=fake.sentence(nb_words=10)
        )
        instance.save()
    queryset = Categories.objects.all()
    goods = Goods.objects.all()
    for good in goods:
        good.categories.add(random.choice(queryset))

def init_good_attrs():
    """初始化商品属性"""
    print('清空 Attrs ')
    Attrs.objects.all().delete()
    print('往 Attrs 添加 数据')
    queryset = Goods.objects.all()
    for i in range(20):
        instance = Attrs.objects.create(
            value=fake.sentence(),
            good=random.choice(queryset)
        )
        instance.save()

def init_good_pics():
    """初始化商品相册"""
    print('清空 Pics ')
    Pics.objects.all().delete()
    print('往 Pics 添加 数据')
    queryset = Goods.objects.all()
    for i in range(20):
        instance = Pics.objects.create(
            big_pic=fake.image_url(width=None, height=None),
            mid_pic=fake.image_url(width=None, height=None),
            small_pic=fake.image_url(width=None, height=None),
            good=random.choice(queryset)
        )
        instance.save()

def init_system_permission():
    """初始权限"""
    print('清空 Permissions ')
    Permissions.objects.all().delete()
    print('往 Permissions 添加 数据')
    df = pd.read_csv('permissions.csv')
    df = df.fillna('')
    for index, row in df.iterrows():
        instance = Permissions.objects.create(
            name=row['name'],
            sign=row['sign'],
            menu=row['menu'],
            method=row['method'],
            path=row['path'],
            desc=row['desc'],
            pid_id=row['pid_id']
        )
        instance.save()

def init_system_roles():
    """初始化角色"""
    print('清空 Roles ')
    Roles.objects.all().delete()
    print('往 Roles 添加 数据')
    roles = ['管理员', '游客', '普通会员', '中级会员', '高级会员', ]
    for role in roles:
        instance = Roles.objects.create(
            name = role,
            desc=fake.paragraph(nb_sentences=3, variable_nb_sentences=True, ext_word_list=None)
        )
        instance.save()
    pers = Permissions.objects.all()
    roles_queryset = Roles.objects.all()
    for per in pers:
        random.choice(roles_queryset).permissions.add(per)

def init_user_user():
    """初始化用户表"""
    print('清空 User ')
    User.objects.all().delete()
    print('往 User 添加 数据')
    educations = [
        'doctor',
        'masters',
        'bachelor',
        'speciality',
        'high_school',
        'junior',
        'primary_school',
        'secrecy'
    ]
    for _ in range(10):
        instance = User.objects.create(
            username=fake.user_name(),
            password=make_password('123456'),
            gender=random.choice([True, False]),
            tel=fake.phone_number(),
            email=fake.free_email(),
            education=random.choice(educations),
        )
        instance.save()
    roles = Roles.objects.all()
    users = User.objects.all()
    for role in roles:
        random.choice(users).role.add(role)

def init_orders_order():
    """初始化订单"""
    print('清空 Orders ')
    Orders.objects.all().delete()
    print('往 Orders 添加 数据')
    for _ in range(20):
        instance = Orders.objects.create(
            number=uuid.uuid1(),
            price=round(random.random() * 100, 2),
            pay=random.choice(range(4)),
            is_send=random.choice([True, False]),
            trade_no='',
            fapiao_company=fake.company(),
            consignee_addr=fake.address(),
            pay_status=random.choice([0,1]),
            user=random.choice(User.objects.all()),
        )
        instance.save()

    goods = Goods.objects.all()
    orders = Orders.objects.all()
    for order in orders:
        order.good.add(random.choice(goods))

def init_user_cart():
    """初始化用户购物车"""
    print('清空 Carts ')
    Carts.objects.all().delete()
    print('往 Carts 添加 数据')
    users = User.objects.all()
    for user in users:
        instance = Carts.objects.create(
            info=fake.text(max_nb_chars=200, ext_word_list=None),
            user=user
        )
        instance.save()
    carts = Carts.objects.all()
    orders = Orders.objects.all()
    for cart in carts:
        cart.order.add(random.choice(orders))


if __name__ == "__main__":
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drf_shop_admin.settings.dev')
    django.setup()

    # 导入自定义模型
    fake = faker.Faker('zh-CN')

    # 商品分类，商品信息，商品相册，商品属性，
    # 初始化商品分类
    from goods.models import Categories, Goods, Attrs, Goods, Pics
    from system.models import Permissions, Roles
    from users.models import User, Carts
    from orders.models import Orders

    from django.contrib.auth.hashers import make_password
    import pandas as pd

    init_good_category()
    init_good_info()
    init_good_attrs()
    init_good_pics()
    init_system_permission()
    init_system_roles()
    init_user_user()
    init_orders_order()
    init_user_cart()
